let house_id = '' // 要删除房屋的id
let house_index = 0 // 要删除房屋在数组中的下标
Page({
  data: {
    dialogVisible: false,
    houseList: [],
  },
  onShow() {
    this.getHouseList()
  },
  // 1. 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败')
    this.setData({
      houseList,
    })
  },

  // 2. 滑块滑动处理
  swipeClose(ev) {
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // 记录要删除房屋的下标和id
      house_id = ev.mark.id
      house_index = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  // 3. 监听对话框的关闭
  dialogClose(ev) {
    // if (ev.detail === 'confirm') {
    //   this.deleteHouse()
    // }
    ev.detail === 'confirm' && this.deleteHouse()
  },

  // 4. 删除房屋
  async deleteHouse() {
    // console.log('要删除房屋的id和下标', house_index, house_id)
    const { code } = await wx.http.delete(`/room/${house_id}`)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')

    // 根据记录的下标取数组中把房屋对象移除
    const { houseList } = this.data
    houseList.splice(house_index, 1)
    this.setData({
      houseList,
    })
  },

  // 5.去房屋详情
  goDetail(ev) {
    wx.navigateTo({
      url: `/house_pkg/pages/detail/index?id=${ev.mark.id}`,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
